import cgi
import os
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write("""
      <html>
        <body>
          <form action="/search" method="post">
            <div><input name="url" rows="3" cols="60"></input></div>
            <div><input type="submit" value="Submit"></div>
          </form>
        </body>
      </html>""")


class SearchResultPage(webapp.RequestHandler):
  def post(self):
    self.response.out.write('<html><body><pre>')
    
    url = self.request.get('url')
    if (not url.startswith('http')):
      url = 'http://' + url 
    escaped_url = cgi.escape(url)
    
    result = urlfetch.fetch('http://badges.del.icio.us/feeds/json/url/data?url=' + 
        escaped_url + 
        '&callback=displayURL')
    if result.status_code == 200:
      self.response.out.write(cgi.escape(result.content))
    
    result = urlfetch.fetch('http://services.digg.com/stories/?link=' + 
        escaped_url + 
        '&appkey=http%3A%2F%2Fwww.example.com&type=xml',
        payload=None, 
        method=urlfetch.GET, 
        headers={'User-Agent': 'Python'})
    if result.result.status_code == 200:
      self.response.out.write(cgi.escape(result.content))
    
    self.response.out.write('</pre></body></html>')

def main():
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/search', SearchResultPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
